package com.cssy.yd.logic.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicPriceDAO;
import com.cssy.yd.logic.entity.LogicPriceDO;
import com.cssy.yd.logic.service.ILogicPriceService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;

@Service("logicPriceService")
public class LogicPriceServiceImpl implements ILogicPriceService{
	@Resource(name = "logicPriceDAO")
	private LogicPriceDAO logicPriceDAO;
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicPriceDO>  list=logicPriceDAO.find(scs);
		rs.setRecordCount(logicPriceDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i =logicPriceDAO.deleteLogicPriceDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicPriceDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicPriceDAO.updateLogicPriceDO(t);
	}

	@Override
	public LogicPriceDO save(LogicPriceDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		logicPriceDAO.insertLogicPriceDO(t);
		return t;
	}

	@Override
	public LogicPriceDO findListById(String id) throws SyBaseException {
		return logicPriceDAO.findLogicPriceDOByPrimaryKey(id);
	}
	
	/**
	 * 输入物料运费计算新的平均单价
	 * @param t 包含有物料信息及所储位置信息的对象
	 * @param freight 运费
	 * @param user 当前登录用户信息
	 * @return
	 * @throws SyBaseException
	 */
	@Override
	public Integer updateAveragePrice(LogicPriceDO t, double freight, User user) throws SyBaseException{
		
		SearchConditions scs = new SearchConditions();
		scs.addCondition(new SearchCondition("code",SearchCondition.OP_EQUAL,t.getCode()));
		scs.addCondition(new SearchCondition("name",SearchCondition.OP_EQUAL,t.getName()));
		scs.addCondition(new SearchCondition("whCode",SearchCondition.OP_EQUAL,t.getWhCode()));
		scs.addCondition(new SearchCondition("hubCode",SearchCondition.OP_EQUAL,t.getHubCode() == null ? null : t.getHubCode()));
		
		SearchResult sr = this.findListByExample(scs);
		if(sr.getResults() == null || sr.getResults().size() < 1){
			throw new SyBaseException("错误:指定位置处无此物料平均单价系信息存在!!");
		}
		
		List<LogicPriceDO>  lpdList = sr.getResults();
		LogicPriceDO lpd = lpdList.get(0);
		double averagePrice = (lpd.getSumprice() * lpd.getSumquantity() + freight) / lpd.getSumquantity(); //计算新的平均单价
		lpd.setSumprice(averagePrice);
		
		return this.update(lpd, user);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}

}
